#define _CRT_SECURE_NO_WARNINGS 1

#include "List.h"

ListNode* ListCreate(LTDateType x)
{
	ListNode* Node = (ListNode*)malloc(sizeof(ListNode));
	if (Node == NULL)
	{
		perror("creat:");
		return 1;
	}
	Node->_date = x;
	Node->_prev = NULL;
	Node->_next = NULL;
	return Node;
}

ListNode* InitList()
{
	ListNode* phead = ListCreate(-1);
	phead->_next = phead;
	phead->_prev = phead;
	return phead;
}

void ListPrint(ListNode* phead)
{
	assert(phead);
	printf("Head(%2d) <==> ", phead->_date);
	ListNode* cur = phead->_next;
	while (cur != phead)
	{
		printf("%2d <==> ", cur->_date);
		cur = cur->_next;
	}
	printf("\n");
}

bool LTEmpty(ListNode* phead)
{
	return phead->_next == phead;
}

void ListPushBack(ListNode* phead, LTDateType x)
{
	assert(phead);
	/*ListNode* newnode = ListCreate(x);
	ListNode* tail = phead->_prev;
	tail->_next = newnode;
	newnode->_next = phead;
	newnode->_prev = tail;
	phead->_prev = newnode;*/
	ListInsert(phead, x);
}

void ListPopBack(ListNode* phead)
{
	assert(phead);
	assert(!LTEmpty(phead));

	/*ListNode* tail = phead->_prev;
	ListNode* prev = tail->_prev;
	prev->_next = phead;
	phead->_prev = prev;
	free(tail);*/
	ListErase(phead->_prev);
}

void ListPushFront(ListNode* phead, LTDateType x)
{
	assert(phead);

	/*ListNode* next = phead->_next;
	ListNode* newnode = ListCreate(x);
	phead->_next = newnode;
	newnode->_prev = phead;
	newnode->_next = next;
	next->_prev = newnode;*/
	ListInsert(phead->_next, x);
}

void ListPopFront(ListNode* phead)
{
	assert(phead);
	assert(!LTEmpty(phead));

	/*ListNode* next = phead->_next->_next;
	next->_prev = phead;
	free(phead->_next);
	phead->_next = next;*/
	ListErase(phead->_next);
}

ListNode* ListFind(ListNode* phead, LTDateType x)
{
	assert(phead);

	ListNode* cur = phead->_next;
	while (cur != phead)
	{
		if (cur->_date == x)
		{
			return cur;
		}
		cur = cur->_next;
	}
	return NULL;
}

void ListInsert(ListNode* pos, LTDateType x)
{
	assert(pos);

	ListNode* prev = pos->_prev;
	ListNode* newnode = ListCreate(x);
	newnode->_next = pos;
	pos->_prev = newnode;
	prev->_next = newnode;
	newnode->_prev = prev;
}

void ListErase(ListNode* pos)
{
	assert(pos);

	ListNode* prev = pos->_prev;
	ListNode* next = pos->_next;
	prev->_next = next;
	next->_prev = prev;
	free(pos);
}

void ListDestory(ListNode* phead)
{
	assert(phead);
	ListNode* cur = phead->_next;
	while (cur != phead)
	{
		ListNode* next = cur->_next;
		free(cur);
		cur = next;
	}
	free(phead);
	//phead = NULL;
}